// arch-tag: bbe6edea-6149-4d16-9d62-226b46bdcd7d
package de.yvert.jingle.impl.reader;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;

import de.yvert.jingle.ldr.LdrImage2D;

public class AWTImageReader
{

final String extension;
final ImageReader imageReader;

public AWTImageReader(String extension)
{
	this.extension = extension;
	this.imageReader = ImageIO.getImageReadersByFormatName(extension).next();
}

public LdrImage2D load(InputStream in) throws IOException
{
	imageReader.setInput(ImageIO.createImageInputStream(in));
	BufferedImage bimg = imageReader.readTile(0, 0, 0);
	
	int width = bimg.getWidth();
	int height = bimg.getHeight();
	
	LdrImage2D result = new LdrImage2D(width, height);
	
/*	Raster raster = bimg.getData();
	int[] data = new int[width*height];
	raster.getPixels(0, 0, width, height, data);
	result.decodeRGB(data);
	*/
	
	// Working, fastest so far, but ugly.
/*	DataBuffer buffer = bimg.getData().getDataBuffer();
	if (buffer instanceof DataBufferByte)
	{
		if (buffer.getNumBanks() != 1) throw new IOException("Unfinished!");
		byte[] data = ((DataBufferByte) buffer).getData();
//		System.out.println(width+" "+height+" "+data.length);
		if (width*height*3 != data.length) throw new IOException("Unfinished!");
		result.decodeBGR(data);
	}
	else
		throw new IOException("Unfinished!");*/
	
	// Working, but VERY slow!
	int[] imgdata = new int[width*height];
	bimg.getRGB(0, 0, width, height, imgdata, 0, width);
	result.decodeARGBint(imgdata);
	
	return result;
}

}
